<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="12">
          
          <a-col :md="6" :sm="24">
            <a-form-item label="计划单号">
              <a-input v-model="queryParam.orderNumber" placeholder="请输入"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="生产单号">
              <a-input v-model="queryParam.scOrderNumber" placeholder="请输入"/>
            </a-form-item>
          </a-col>
          <a-col :md="5" :sm="24">
            <a-form-item label="状态">
              <a-select v-model="queryParam.executeStatus" placeholder="请选择">
                <a-select-option :value="item.value" v-for="item in executeStatusList" :key="item.value">
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          
          <a-col :md="6" :sm="24">
            <a-form-item>
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="handleResetSearch">重置</a-button>
            </span>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    
    <s-table
      ref="table"
      size="default"
      :columns="columns"
      :data="loadData"
      :scroll="{
        x: 1200
      }"
      :alert="true"
      :rowKey="(record) => record.orderId"
      :rowSelection="rowSelection"
    >
      <div slot="executeStatus" slot-scope="text, record">
        <a-tag color="blue">
          {{ getExecuteStatusLabel(text) }}
        </a-tag>
      </div>
      <div slot="action" slot-scope="text, record">
        <div>
          <a @click="backStoreDetailModal.show(record)">反执行详情</a>
          <a-divider type="vertical"/>
          <a @click="operationLog.show(record)">操作日志</a>
        </div>
        
        <!--   待审核     -->
        <div v-if="+record.executeStatus===1">
          <a class="text-danger hover:text-danger" @click="handleCancelOrAgreePlan(4,record)"
             v-if="hasPerm('emsReturnPlanOrder:cancel')">取消</a>
          <a-divider type="vertical" v-if="hasPerm('emsReturnPlanOrder:audit')"/>
          <a class="text-success hover:text-success" @click="handleCancelOrAgreePlan(2,record)"
             v-if="hasPerm('emsReturnPlanOrder:audit')">同意</a>
          <a-divider type="vertical" v-if="hasPerm('emsReturnPlanOrder:audit')"/>
          <a class="text-danger hover:text-danger" @click="handleRefuseOrRelaunchPlan('refuse',record)"
             v-if="hasPerm('emsReturnPlanOrder:audit')">拒绝</a>
        </div>
        
        <!--   已通过     -->
        <div v-if="+record.executeStatus===2">
          <a @click="handleWithdrawAudit(record)" v-if="hasPerm('emsReturnPlanOrder:revokeReview')">撤销审核</a>
          <a-divider type="vertical" v-if="hasPerm('emsReturnPlanOrder:confirm')"/>
          <a @click="handleConfirmWarehousing(record)" v-if="hasPerm('emsReturnPlanOrder:confirm')">确认反执</a>
        </div>
        
        <!--   已拒绝     -->
        <div v-if="+record.executeStatus===3">
          <a @click="handleWithdrawAudit(record)" v-if="hasPerm('emsReturnPlanOrder:revokeReview')">撤销审核</a>
          <a-divider type="vertical" v-if="hasPerm('emsReturnPlanOrder:reissue')"/>
          <a @click="handleRefuseOrRelaunchPlan('relaunch',record)"
             v-if="hasPerm('emsReturnPlanOrder:reissue')">重新发起</a>
        </div>
        
        <!--   已取消     -->
        <div v-if="+record.executeStatus===4">
          <a @click="handleRefuseOrRelaunchPlan('relaunch',record)"
             v-if="hasPerm('emsReturnPlanOrder:reissue')">重新发起</a>
        </div>
      
      </div>
    </s-table>
    
    <operation-log ref="operationLog"/>
    <back-store-detail-modal ref="backStoreDetailModal"/>
    <relaunch-or-refuse-modal :operate-type="operateType" ref="relaunchOrRefuseModal" @handle-ok="handleOk"/>
  
  </a-card>
</template>

<script lang="tsx">
import {Component, Vue, Ref} from "vue-property-decorator";
import {STable} from '@/components'
import OperationLog from './operationLog.vue'
import BackStoreDetailModal from './reverseExecuteRecordDetailModal.vue'
import RelaunchOrRefuseModal from './relaunchOrRefuseModal.vue'
import {
  emsPlanOrderPage, emsReturnPlanOrderAudit,
  emsReturnPlanOrderCancel, emsReturnPlanOrderConfirm, emsReturnPlanOrderRevokeReview
} from "@/api/modular/main/emsordermaterial/emsOrderMaterialManage";

type Record = {
  materialId: string,
  materialCode: string,
  materialName: string,
  number: number,
  completedNumber: number,
}

@Component({
  components: {
    STable,
    OperationLog,
    BackStoreDetailModal,
    RelaunchOrRefuseModal
  }
})
export default class EmsMaterialBackStorePlan extends Vue {
  @Ref() readonly table!: any
  @Ref() readonly operationLog!: OperationLog
  @Ref() readonly backStoreDetailModal!: BackStoreDetailModal
  @Ref() readonly relaunchOrRefuseModal!: RelaunchOrRefuseModal
  
  columns = [
    {
      align: 'center',
      
      title: '序号', width: '80px',
      customRender: (text, record, index) => `${index + 1}`
    },
    {
      align: 'center',
      title: '计划单号',
      dataIndex: 'orderNumber'
    }, {
      align: 'center',
      title: '生产单号',
      dataIndex: 'scOrderNumber'
    },
    {
      align: 'center',
      title: '状态',
      dataIndex: 'executeStatus',
      scopedSlots: {customRender: 'executeStatus'}
      
    }, {
      align: 'center',
      title: '反执行原因',
      dataIndex: 'planReason'
    }, {
      align: 'center',
      title: '创建人',
      dataIndex: 'createUserName'
    }, {
      align: 'center',
      title: '创建时间',
      dataIndex: 'createTime'
    }, {
      align: 'center',
      title: '审核人',
      dataIndex: 'auditMan'
    }, {
      align: 'center',
      title: '审核时间',
      dataIndex: 'auditTime'
    }, {
      align: 'center',
      title: '拒绝原因',
      dataIndex: 'rejectReason'
    },
    {
      align: 'center',
      title: '操作',
      dataIndex: '',
      width: '200px',
      scopedSlots: {customRender: 'action'}
    }
  ]
  executeStatusList = [
    {label: '全部', value: 0},
    {label: '待审核', value: 1},
    {label: '通过', value: 2},
    {label: '拒绝', value: 3},
    {label: '取消', value: 4},
    {label: '已反执', value: 5},
  ]
  operateType = ''
  queryParam = {
    orderNumber: '',
    scOrderNumber: '',
    executeStatus: 0
  }
  selectedRowKeys = []
  selectedRows = []
  rowSelection = {
    getCheckboxProps: (record: Record) => ({
      props: {
        disabled: record.completedNumber > 0,
        name: record.materialCode,
      },
    }),
    selectedRowKeys: this.selectedRowKeys,
    onChange: this.onSelectChange
  }
  
  getExecuteStatusLabel(executeStatus) {
    return this.executeStatusList.find(item => +item.value === +executeStatus)?.label
  }
  
  // 加载数据方法 必须为 Promise 对象
  loadData(parameter: { pageNo: number, pageSize: number }) {
    const params = {
      ...this.queryParam,
      executeStatus: this.queryParam.executeStatus === 0 ? '' : this.queryParam.executeStatus,
      
      // 订单类型 1退库 2返执行
      orderType: 2,
    }
    return emsPlanOrderPage(params, parameter).then((res) => {
      return res.data
    })
  }
  
  
  handleOk() {
    this.table.refresh()
    this.table.clearSelected()
  }
  
  handleResetSearch() {
    this.queryParam = {
      orderNumber: '',
      scOrderNumber: '',
      executeStatus: 0
    }
    this.table.refresh()
    
  }
  
  onSelectChange(selectedRowKeys, selectedRows) {
    this.selectedRowKeys = selectedRowKeys
    this.selectedRows = selectedRows
  }
  
  handleRefuseOrRelaunchPlan(operateType, record) {
    this.operateType = operateType
    this.$nextTick(() => {
      this.relaunchOrRefuseModal.show(record)
      
    })
  }
  
  
  // 确认反执行
  handleConfirmWarehousing(record) {
    this.$confirm({
      title: '系统提示',
      content: '是否确认反执？',
      onOk: () => {
        emsReturnPlanOrderConfirm({
          orderId: record.orderId
        }).then(res => {
          //@ts-ignore
          if (res.success) {
            this.$message.info('确认反执成功')
            this.handleOk()
          } else {
            //@ts-ignore
            this.$message.error('确认反执失败：' + res.message)
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
    
  }
  
  
  // 撤销审核
  handleWithdrawAudit(record) {
    this.$confirm({
      title: '系统提示',
      content: '当前撤销审核后，将对生产单所有的入库记录和发货记录进行反执行，请谨慎操作',
      onOk: () => {
        emsReturnPlanOrderRevokeReview({
          orderId: record.orderId
        }).then(res => {
          //@ts-ignore
          if (res.success) {
            this.$message.info('撤销审核成功')
            this.handleOk()
          } else {
            //@ts-ignore
            this.$message.error('撤销审核失败：' + res.message)
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
    
  }
  
  
  // 取消或通过审核
  handleCancelOrAgreePlan(executeStatus, record) {
    // executeStatus 1待审核 2通过 3拒绝 4取消 5已入库
    // 通过
    if (executeStatus === 2) {
      this.$confirm({
        title: '系统提示',
        content: '是否确认同意？',
        onOk: () => {
          emsReturnPlanOrderAudit({
            orderId: record.orderId,
            executeStatus
          }).then(res => {
            //@ts-ignore
            if (res.success) {
              this.$message.info('同意成功')
              this.handleOk()
            } else {
              //@ts-ignore
              this.$message.error('同意失败：' + res.message)
            }
          })
        },
        onCancel() {
          console.log('Cancel');
        },
      });
      
    }
    
    // 取消
    if (executeStatus === 4) {
      this.$confirm({
        title: '系统提示',
        content: '是否确认取消？',
        onOk: () => {
          emsReturnPlanOrderCancel({
            orderId: record.orderId,
          }).then(res => {
            //@ts-ignore
            if (res.success) {
              this.$message.info('取消成功')
              this.handleOk()
            } else {
              //@ts-ignore
              this.$message.error('取消失败：' + res.message)
            }
          })
        },
        onCancel() {
          console.log('Cancel');
        },
      });
      
    }
    
  }
  
  
}
</script>

<style lang="less">
.table-operator {
  margin-bottom: 18px;
}

button {
  margin-right: 8px;
}
</style>
